from django.shortcuts import render
from cake.models import CakesModel,TasteCakeModel,CateCakeModel,BannerModel
from rest_framework.views import APIView
from rest_framework.response import Response
from cake.cakeser import CakeSerializer, TasteSerializer, CateSerializer, BannerSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from django.db.models import Q

# Create your views here.
class CateView(ModelViewSet):
    queryset = CateCakeModel.objects.all()
    serializer_class = CateSerializer
class TasteView(ListAPIView):
    queryset = TasteCakeModel.objects.all()
    serializer_class = TasteSerializer
    def get_queryset(self):
        query = Q()
        cname = self.request.query_params.get('cname')
        if cname:
            query &= Q(cname=cname)
        return self.queryset.filter(query)
class CakeView(ListAPIView):
    queryset = CakesModel.objects.all()
    serializer_class = CakeSerializer
    def get_queryset(self):
        query = Q()
        id = self.request.query_params.get('id')
        cate = self.request.query_params.get('cate')
        taste = self.request.query_params.get('taste')
        if id:
            query &= Q(id=id)  # 单个id查询
        if cate:
            query &= Q(cate_id=cate)
        if taste:
            query &= Q(taste_id=taste)
        return self.queryset.filter(query)
class DetialCakeView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        if id is None:
            return Response({"message":"id不能为空",'code':400})
        else:
            cake = CakesModel.objects.filter(id=id).first()
            serializer = CakeSerializer(cake)
            return Response(serializer.data)
class BannerView(APIView):
    def get(self, request):
        banners = BannerModel.objects.all()
        serializer = BannerSerializer(banners, many=True)
        return Response(serializer.data)
class FinderView(APIView):
    def get(self, request):
        kname  = request.GET.get('kname')
        print(kname,11122)
        cakes = CakesModel.objects.filter(kname__contains=kname).all()
        ser = CakeSerializer(cakes,many=True)
        return Response(ser.data)
class SingleCake(APIView):
    def get(self, request):
        id = request.GET.get('id')
        cake = CakesModel.objects.get(id=id)
        ser = CakeSerializer(cake)
        return Response(ser.data)
# sk-d308690e79244ce59e9aac3a3d6b1189




















